package com.fjl.list.leetcode2;

import java.util.Stack;

/**
 * @Description
 * @Author: 01195
 * @Date: 2025/2/20 10:58
 */
public class AddBinary67 {

    public String addBinary(String a, String b) {
        // 把链表元素转入栈中
        Stack<Integer> stk1 = new Stack<>();
        for (int i = 0; i < a.length(); i++) {
            stk1.push(Character.getNumericValue(a.charAt(i)));
        }
        Stack<Integer> stk2 = new Stack<>();
        for (int i = 0; i < b.length(); i++) {
            stk2.push(Character.getNumericValue(b.charAt(i)));
        }
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        while (!stk1.isEmpty() || !stk2.isEmpty() || carry > 0) {
            // 先加上上次的进位
            Integer val = carry;
            if (!stk1.isEmpty()) {
                val += stk1.pop();
            };
            if (!stk2.isEmpty()) {
                val += stk2.pop();
            }
            carry = val / 2;
            val %= 2;
            sb.insert(0, val);
        }
        return sb.toString();
    }
}
